package com.taobao.askwho.db.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;

import org.apache.log4j.Logger;

import com.taobao.askwho.db.base.MysqlRouteBase;
import com.taobao.askwho.po.UserInfo;
import com.taobao.askwho.utils.DateUtil;

public class UserInfoDao extends MysqlRouteBase {
	private static  Logger logger = Logger.getLogger(UserInfoDao.class);
	public UserInfo getUrlInfoById(String uuid) {
		
		String sql = "select * from user_info where uuid = ?";
		try {
			final UserInfo user = new UserInfo();
			this.query(sql,new Object[]{uuid}, new SqlCallBack(){
				public void readerRows(ResultSet rs) throws SQLException {
					setValueForPo(user, rs);
				}
			});
			return user;
		} catch (Exception e) {
			logger.error("",e);
		}
		return null;
	}
	
	public UserInfo getUserInfoByEmail(String email) {
		
		String sql = "select * from user_info where user_email = ?";
		try {
			final UserInfo user = new UserInfo();
			this.query(sql,new Object[]{email}, new SqlCallBack(){
				public void readerRows(ResultSet rs) throws SQLException {
					setValueForPo(user, rs);
				}
			});
			return user;
		} catch (Exception e) {
			logger.error("",e);
		}
		return null;
	}
	
	private void setValueForPo(UserInfo userInfo, ResultSet rs) throws SQLException {
		userInfo.setUuid(rs.getString("uuid"));
		userInfo.setUserName(rs.getString("user_name"));
		userInfo.setUserEmail(rs.getString("user_email"));
		userInfo.setUserWangwang("user_wangwang");
		userInfo.setCreateTime(new Date());	//FIXME 读取sql.date后，json显示有问题
		userInfo.setLastLoginTime(new Date());	//
		userInfo.setVisitTimes(rs.getInt("visit_times"));
		userInfo.setPassword(rs.getString("password"));
		//显示到时分秒
		//userInfo.setCreateTimeStr(DateUtil.getStringOfSqlDate(rs.getDate("create_time")));
		//userInfo.setLastLoginTimeStr(DateUtil.getStringOfSqlDate(rs.getDate("last_login_time")));
		userInfo.setCreateTimeStr(DateUtil.cutLastNumOfSqlTimeString(rs.getString("create_time")));
		userInfo.setLastLoginTimeStr(DateUtil.cutLastNumOfSqlTimeString(rs.getString("last_login_time")));		
	}
	
	public void addNewUser(UserInfo user) throws SQLException {
		String sql = "INSERT INTO user_info(UUID,user_name,user_email,user_wangwang,create_time,last_login_time,visit_times,password)VALUE(?,?,?,?,?,?,?,?)";
		this.execute(sql,new Object[]{user.getUuid(),user.getUserName(),user.getUserEmail(),user.getUserWangwang(),user.getCreateTime(),user.getLastLoginTime(),user.getVisitTimes(),user.getPassword()});
	}
	
	public void updateUser(UserInfo user) throws SQLException {
		String sql = "UPDATE user_info SET user_name = ?,user_wangwang = ?, last_login_time = ?, visit_times = ? WHERE user_email = ?,password=?";
		this.execute(sql,new Object[]{user.getUserName(),user.getUserWangwang(),user.getLastLoginTime(),user.getVisitTimes(),user.getUserEmail(),user.getPassword()});
	}
}
